package com.example.download.fragment

import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.download.Help
import com.example.download.R
import com.example.download.ViewModel.CViewModel
import com.example.download.adapter.downloaded_itemAdapter
import com.example.download.bean.downloaded_item

class CFragment : Fragment() {
    private lateinit var iv_dle_add: ImageView
    private lateinit var iv_fc_dle_frame: ImageView
    private lateinit var tv_fc_dle_nt: TextView
    private lateinit var downloadedView: RecyclerView
    private lateinit var downloadedItemAdapter: downloaded_itemAdapter
    private lateinit var downloadedItemList: MutableList<downloaded_item>
    private lateinit var cl_fc_button : ConstraintLayout
    private lateinit var cViewModel: CViewModel
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_c, container, false)
    }
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

        cViewModel = ViewModelProvider(this).get(CViewModel::class.java)
        downloadedView = view.findViewById(R.id.fc_recyclerViewC)
        downloadedView.layoutManager = LinearLayoutManager(requireContext())
        downloadedItemAdapter = downloaded_itemAdapter(mutableListOf())
        downloadedView.adapter = downloadedItemAdapter

        iv_fc_dle_frame = view.findViewById(R.id.iv_fc_dle_frame)
        tv_fc_dle_nt = view.findViewById(R.id.tv_fc_dle_nt)

        cViewModel.downloadedItemList.observe(viewLifecycleOwner,Observer{itemList ->
            downloadedItemAdapter.updateData(itemList)
            if (itemList.isNotEmpty()){
                iv_fc_dle_frame.visibility = View.GONE
                tv_fc_dle_nt.visibility = View.GONE
            }else {
                iv_fc_dle_frame.visibility = View.VISIBLE
                tv_fc_dle_nt.visibility = View.VISIBLE
            }
        })

        iv_dle_add = view.findViewById(R.id.iv_dle_add)
        iv_dle_add.setOnClickListener {
            cViewModel.addNewItem()
            iv_fc_dle_frame.visibility = View.GONE
            tv_fc_dle_nt.visibility = View.GONE
        }
        cl_fc_button = view.findViewById(R.id.cl_fc_button)
        cl_fc_button.setOnClickListener {
            val intent = Intent(requireContext(), Help::class.java)
            startActivity(intent)
        }

    }
}